"""
    Author:
    Date: 2019-10-26

    快速回复管理类
"""

from entities.consts import *
from utils import db


def get_fast_reply_list():
    """ 获取快速回复列表 """
    sql = f'''
        SELECT      *
        FROM        cmf_config_fast_reply
        ORDER BY    enabled DESC,
                    orderno,
                    id;
    '''
    data = db.query_data_from_db(sql)
    return data if data else []


def enable_fast_reply(fast_reply_id):
    """ 启用动态表情 """
    sql = f'''
        UPDATE      cmf_config_fast_reply
        SET         enabled=1
        WHERE       fast_reply_id={fast_reply_id} AND
                    enabled=0;
    '''
    affected_rows = db.execute_sql(sql)
    return affected_rows > 0


def disable_fast_reply(fast_reply_id):
    """ 禁用动态表情 """
    sql = f'''
        UPDATE      cmf_config_fast_reply
        SET         enabled=0
        WHERE       fast_reply_id={fast_reply_id} AND
                    enabled=1;
    '''
    affected_rows = db.execute_sql(sql)
    return affected_rows > 0


def new_fast_reply(id, message, orderno):
    """ 添加新的动态表情 """
    sql = '''
        INSERT INTO cmf_config_fast_reply
        SET         fast_reply_id=%(id)s,
                    message=%(message)s,
                    orderno=%(orderno)s,
                    enabled=0
    '''
    params = {
        'id': str(id),
        'message': message,
        'orderno': str(orderno),
    }
    affected = db.execute_sql(sql, params)
    return affected == 1


def edit_fast_reply(fast_reply_id, message, orderno):
    """ 编辑动态表情 """
    sql = f'''
        UPDATE      cmf_config_fast_reply
        SET         message=%(message)s,
                    orderno=%(orderno)s
        WHERE       fast_reply_id=%(fast_reply_id)s;
    '''
    params = {
        'fast_reply_id': str(fast_reply_id),
        'message': message,
        'orderno': str(orderno),
    }
    affected_rows = db.execute_sql(sql, params)
    return affected_rows > 0


def get_max_fast_reply_id():
    """ 获取最大的动态表情id """
    sql = '''
        SELECT    MAX(fast_reply_id) AS max_fast_reply_id
        FROM      cmf_config_fast_reply;
    '''
    data = db.query_data_from_db(sql)
    return data[0]['max_fast_reply_id'] if data else 0


def get_fast_reply(fast_reply_id):
    """ 根据id获取快速回复 """
    sql = f'''
        SELECT      *
        FROM        cmf_config_fast_reply
        WHERE       fast_reply_id={fast_reply_id};
    '''
    data = db.query_data_from_db(sql)
    return data[0] if data else None


if __name__ == '__main__':
    print('ok')
